import React, { FC, useEffect, useState, useCallback, useRef } from "react";
import { connect } from "react-redux";
import action from "../../../store/Actions";
import Navigation from "../../../component/Navigation";
import { exportExcel, importsExcel } from "../../../utils/excel";
import Table from "src/component/table";
import MyAlert from "../../../component/MyAlert";
import { Button, Space, Input, Pagination, Select } from "antd";
import Dormitory from './dormitory'
import {
  PlusCircleOutlined,
  DownloadOutlined,
  UploadOutlined,
  AppstoreOutlined,
  CompressOutlined,
  EditTwoTone,
  DeleteTwoTone,
} from "@ant-design/icons";
import "./index.less";
interface State {
  dataList: any;
  DormitoryList: any;
  getDormitoryList: Function
 
}  
const DormitoryManger: FC<DormitoryMangerState> = (props: any) => {
  console.log(props);
  
  const { Option } = Select;
   // console.log(props);
   const [state, setSate] = React.useState({
    dataList: [],
    keyPath:['wbj', '网站工程']
  });
  useEffect(()=>{
    let { getDormitoryList,getlist} = props;
     getlist({val:'空值'})
     getDormitoryList();
  },[])

  //试图切换
  const [pattern, setPattern] = useState(false);
  //校区宿舍名单
  const [campus, setCampus] = useState([]);
  //设置表格大小
  const [dataLength, setDataLength] = useState(0);
  //设置行标题
  const [columns, setColumns] = useState([]);
  //弹框是否显示
  const [isAdd, setIsAdd] = useState(false);
  //设置弹框标题
  const [title, setTitle] = useState("");
  //设置表格头
  const [header, setHeader] = useState([
    {
      title: "编号",
      dataIndex: "id",
      key: "id",
      className: "text-monospace",
    },
    {
      title: "宿舍号",
      dataIndex: "DormitoryNo",
      key: "DormitoryNo",
    },
    {
      title: "容纳人数",
      dataIndex: "max_number",
      key: "max_number",
    },
    {
      title: "费用",
      dataIndex: "money",
      key: "money",
    },
    {
      title: "现住人数",
      dataIndex: "now_number",
      key: "now_number",
    },
    {
      title: "差评次数",
      dataIndex: "c_count",
      key: "c_count",
    },
    {
      title: "好评次数",
      dataIndex: "count",
      key: "count",
    },
    {
      title: "评级",
      dataIndex: "evaluate",
      key: "evaluate",
    },
    {
      title: "今日值日生",
      dataIndex: "now_dusty",
      key: "now_dusty",
    },
    {
      title: "值日生表",
      dataIndex: "dusty_plan",
      key: "dusty_plan",
    },
  ]);
  //一级标题
  const [collTitle,setCollTitle] = useState("网站工程");
  // 二级标题
  const [camTitle,setCamTitle] = useState("wbj");
  //获取导入元素
  const importEl = useRef<any>();

  //修改
  const [edit, setEdit] = useState(false);
  //删除
  const [del, setDel] = useState(false);
  //获取当前点击对象
  const [editObj, setEditObj] = useState<any>({});
  //设置学院
  const [college, setCollege] = useState("");
  //设置校区
  const [campuses, setCampuses] = useState("");
  // 设置宿舍楼号
  const [dorm, setDorm] = useState("");
  //设置宿舍号
  const [dormitoryNo, setDormitoryNo] = useState("");
  //设置容纳人数
  const [maxNumber, setMaxNumber] = useState(null);
  //设置费用
  const [money, setMoney] = useState(0);
  //校区选择
  const [campusOption, setCampusOption] = useState([]);
  //设置现有人数
  const [nowNumber, setNowNumber] = useState(null);
  //好评次数
  const [count, setCount] = useState(null);
  //差评次数
  const [c_count, setC_count] = useState(null);
  //设置当前页码
  const [current, setCurrent] = useState(1);
  //设置页码条数
  const [size, setSize] = useState(10);
  //确定添加宿舍
  const okAdd = () => {
    const { addDormitory } = props;
    let obj = {
      college: college,
      campus: campuses,
      dorm_number: dorm,
      DormitoryNo: dormitoryNo,
      max_number: maxNumber,
      money: money,
    };
    addDormitory(obj);
    setIsAdd(false);
  };
  //取消添加
  const cancelAdd = () => {
    setIsAdd(false);
  };

  //确定修改
  const okEdit = () => {
    // console.log(c_count);

    let obj = {
      id: editObj.id,
      college: editObj.college,
      campus: editObj.campus,
      DormitoryNo: editObj.DormitoryNo,
      max_number: maxNumber ? maxNumber : editObj.max_number,
      now_number: nowNumber ? nowNumber : editObj.now_number,
      money: money ? money : editObj.money,
      count: count ? count : editObj.count,
      c_count: c_count ? c_count : editObj.c_count,
    };
    // console.log(obj);
    setEdit(false);
  };
  //取消修改
  const cancelEdit = () => {
    setEdit(false);
  };

  //确定删除
  const okDel = () => {
    setDel(false);
  }

  //取消删除
  const cancelDel = () => {
    setDel(false);
  }


  const handleChange = (value) => {
    props.dormitoryReducer.DormitoryList.forEach((item) => {
      if (item.college === value) {
        setCampusOption(JSON.parse(item.campus));
      }
    });
    setCollege(value);
  };

  function getWeekDate() {
    let now = new Date();
    let day = now.getDay();
    let weeks = [
      "星期日",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六",
    ];
    let week = weeks[day];
    return week;
  }

  //封装表格数据转换
  const TableList=(college:string, campus:string, data:any)=>{
    return data.map((item:any) => {
      return {
        id: item.id,
        college: college,
        campus: campus,
        DormitoryNo: item.DormitoryNo,
        max_number: item.max_number,
        money: item.money,
        now_number: item.now_number,
        c_count: item.c_count,
        count: item.count,
        evaluate: item.evaluate,
        now_dusty: now_dusty(item.person),
        dusty_plan: "安排",
      };
    });
  }
  //根据时间判断当日值日生
  function now_dusty(item) {
    let name = "";
    item.forEach((ite) => {
      if (ite.timer === getWeekDate()) {
        name = ite.name;
      }
    });
    return name;
  }

  //获取所有数据列表
  useEffect(() => {
    let { getDormitoryList,getlist } = props;
    getDormitoryList();
    getlist({val:'空值'})
  }, [props.getDormitoryList]);

  useEffect(() => {
    const { DormitoryList } = props.dormitoryReducer;
    if (DormitoryList.length > 0) {
      let data = JSON.parse(DormitoryList[0].campus)[0].dormList;
      setDataLength(data.length);
      let start = (current - 1) * size;
      let end = start + size;
      setCampus(
        TableList(
          DormitoryList[0].college,
          JSON.parse(DormitoryList[0].campus)[0].sid,
          data.slice(start, end)
        )
      );
    }
  }, [props.dormitoryReducer]);

  useEffect(() => {
    let columns = [
      {
        title: "宿舍号",
        dataIndex: "DormitoryNo",
        key: "DormitoryNo",
        width: "150px",
      },
      {
        title: "容纳人数",
        dataIndex: "max_number",
        key: "max_number",
        width: "150px",
      },
      {
        title: "费用",
        dataIndex: "money",
        key: "money",
        width: "150px",
      },
      {
        title: "现住人数",
        dataIndex: "now_number",
        key: "now_number",
        width: "150px",
      },
      {
        title: "今日值日生",
        dataIndex: "now_dusty",
        key: "now_dusty",
        width: "150px",
      },
      {
        title: "操作",
        key: "action",
        width: "120px",
        render: (text, record) => (
          <Space size="middle">
            <EditTwoTone
              onClick={(text) => {
                setEdit(true);
                setTitle("修改");
                setEditObj(record);
              }}
            />
            <DeleteTwoTone twoToneColor="#ff4d4f" onClick={(text) => {
              setDel(true);
              setTitle("删除");
              setEditObj(record);
            }} />
          </Space>
        ),
      },
    ];
    setColumns(columns);
  }, [campus, props.dormitoryReducer]);
  
  
  //点击导航获取对应的数据
  const handleClick = useCallback(
    (e) => {
      const { keyPath } = e;
      console.log(e);
      let { DormitoryList } = props.dormitoryReducer;
      let result = DormitoryList.filter(
        (item) => item.college.indexOf(keyPath[keyPath.length - 1]) !== -1
      );
      let data = JSON.parse(result[0].campus).filter((item) => {
        return item.sid === keyPath[0];
      })[0].dormList;
      setDataLength(data.length);
      let start = (current - 1) * size;
      let end = start + size;
      setCampus(
        TableList(
          keyPath[keyPath.length - 1],
          keyPath[0],
          data.slice(start, end)
        )
      );
      setSate({
        ...state,
        keyPath:keyPath,
      })
      if(keyPath.length>0){
        props.getlist(keyPath)
      }
    },
    [props.dormitoryReducer, current, size]
  );

  //分页
  function changeCurrent(pageNumber) {
    // console.log(campus.length);

    setCurrent(pageNumber);
  }
  const ShowSize = (current, size) => {
    setCurrent(current);
    setSize(size);
  };

  return (
    
    <div className="DormitoryManger">
      {/* 头部 */}
      <header>
        <ul>
          <li>
            <Button
              type="primary"
              icon={<PlusCircleOutlined />}
              onClick={() => {
                setIsAdd(true);
                setTitle("创建宿舍");
              }}
            >
              创建宿舍
            </Button>
          </li>
          <li>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={() => {
                importEl.current.click();
              }}
            >
              导入
            </Button>
            <input type="file" ref={importEl} accept=".xls,.xlsx" onChange={(e)=>{
              const { importDate } = props;
              importsExcel(e).then((res:any)=>{
                let arr = res.map((item) => {
                  return {
                    id: item.id,
                    college:item.college,
                    campus:item.campus,
                    DormitoryNo: item.DormitoryNo,
                    max_number: item.max_number,
                    money: item.money,
                    now_number: item.now_number,
                    c_count: item.c_count,
                    count: item.count,
                    evaluate: item.evaluate
                  };
                });
                importDate({addList:arr});
              })
            }}/>
          </li>
          <li>
            <Button
              type="primary"
              icon={<UploadOutlined />}
              onClick={() => {
                exportExcel(header, campus, "宿舍学生人员信息.xlsx");
              }}
            >
              导出
            </Button>
          </li>
          <li>
            <Button
              type="primary"
              icon={<AppstoreOutlined />}
              onClick={() => {
                setPattern(!pattern);
              }}
            >
              视图切换
            </Button>
          </li>
          <li>
            <Button type="primary" icon={<CompressOutlined />}>
              全览
            </Button>
          </li>
        </ul>
      </header>
      {/* 中间部分 */}
      <div className="main">
        {/* 左边侧边导航 */}
        {/* 中间内容部分 */}

        <aside>
          <Navigation
            // 总数据数据
            data={props.dormitoryReducer.DormitoryList}
            // 一标题的属性（字段数组类型）"college":["网站工程","人工智能"]
            primaryNavigationProps="college"
            //二级标题的属性（字段）"college":["网站工程","人工智能"]
            childrenProps="campus"
            //设置二级标题对象属性
            childrenItem="name"
            //获取当前子级标题的key
            handleClick={handleClick}
            //设置子级标题的key值
            setChildrenKey="sid"
            //设置样式
            style={{ width: "100%", height: 600, border: "1px solid #ccc" }}
          ></Navigation>
        </aside>
        {/* 中间内容部分 */}
        <div className="content">
          {/* 内容 */}
          {pattern ? (
            <Dormitory  keyPath={state.keyPath} datalist={props.dormitoryReducer.dataList} dormitoryReducer /> 
            // props.dormitoryReducer.list
          ) : (
            <Table
              studentData={campus}
              columns={columns}
              style={{ height: "500px" }}
            ></Table>
          )}
        </div>
      </div>
      {/* 底部分页 */}
      <footer>
        <Pagination
          showQuickJumper
          defaultCurrent={current}
          defaultPageSize={10}
          showSizeChanger={campus.length > 10 ? true : false}
          pageSizeOptions={["10", "15", "20"]}
          total={dataLength}
          onChange={changeCurrent}
          onShowSizeChange={ShowSize}
        />
      </footer>
      <MyAlert
        isModalVisible={isAdd}
        handleOk={okAdd}
        handleCancel={cancelAdd}
        title={title}
        cancelText="取消"
        okText="确定"
      >
        <div className="information">
          <ul>
            <li>
              <span>学院 :</span>
              <Select
                placeholder="请选择学院"
                value={college}
                onChange={handleChange}
              >
                {props.dormitoryReducer.DormitoryList.map((item) => {
                  return (
                    <Option key={item.id} value={item.college}>
                      {item.college}
                    </Option>
                  );
                })}
              </Select>
            </li>
            <li>
              <span>校区 :</span>
              <Select
                placeholder="请选择校区"
                value={campuses}
                onChange={(value) => {
                  setCampuses(value);
                }}
              >
                {campusOption.map((item) => {
                  return (
                    <Option key={item.sid} value={item.name}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </li>
            <li>
              <span>楼层号 :</span>
              <Input
                placeholder="请输入楼层号"
                onBlur={(e) => {
                  setDorm(e.target.value);
                }}
              />
            </li>
            <li>
              <span>宿舍号 :</span>
              <Input
                placeholder="请输入宿舍号"
                onBlur={(e) => {
                  setDormitoryNo(e.target.value);
                }}
              />
            </li>
            <li>
              <span>容纳人数 :</span>
              <Input
                placeholder="请输入容纳人数"
                onBlur={(e) => {
                  setMaxNumber(Number(e.target.value));
                }}
              />
            </li>
            <li>
              <span>费用 :</span>
              <Input
                placeholder="请输入费用"
                onChange={(e) => {
                  setMoney(Number(e.target.value));
                }}
              />
            </li>
          </ul>
        </div>
      </MyAlert>
      <MyAlert
        isModalVisible={edit}
        handleOk={okEdit}
        handleCancel={cancelEdit}
        title={title}
        cancelText="取消"
        okText="确定"
      >
        <div className="information">
          <ul>
            <li>
              <span>宿舍号 :</span>
              <span>{editObj.DormitoryNo || ""}</span>
            </li>
            <li>
              <span>容纳人数 :</span>
              <Input
                placeholder={
                  editObj.max_number ? editObj.max_number : "请输入容纳人数"
                }
                onBlur={(e) => {
                  setMaxNumber(Number(e.target.value));
                }}
              />
            </li>
            <li>
              <span>现住人数 :</span>
              <Input
                placeholder={
                  editObj.now_number ? editObj.now_number : "请输入现住人数"
                }
                onBlur={(e) => {
                  setNowNumber(Number(e.target.value));
                }}
              />
            </li>
            <li>
              <span>费用 :</span>
              <Input
                placeholder={editObj.money ? editObj.money : "请输入费用"}
                onBlur={(e) => {
                  setMoney(Number(e.target.value));
                }}
              />
            </li>
            <li>
              <span>好评次数 :</span>
              <Input
                placeholder={editObj.count ? editObj.count : "请输入好评次数"}
                onBlur={(e) => {
                  setCount(e.target.value);
                }}
              />
            </li>
            <li>
              <span>差评次数 :</span>
              <Input
                placeholder={
                  editObj.c_count ? editObj.c_count : "请输入差评次数"
                }
                onBlur={(e) => {
                  setC_count(e.target.value);
                }}
              />
            </li>
          </ul>
        </div>
      </MyAlert>
      <MyAlert
        isModalVisible={del}
        handleOk={okDel}
        handleCancel={cancelDel}
        title={title}
        cancelText="取消"
        okText="确定"
      >
        <h3 style={{fontWeight:"bolder"}}>你确定要删除该条信息吗?</h3>
      </MyAlert>
    </div>
  );
};
export default connect(state => state, action.dormitoryActions)(DormitoryManger);

